package com.zfast.config.handler;

import cn.hutool.json.JSONUtil;
import com.zfast.config.entity.User;
import com.zfast.config.entity.Role;
import com.zfast.config.service.RoleService;
import com.zfast.config.vo.CommonResult;
import com.zfast.config.constant.SessionKeyConst;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @Auther: wdd
 * @Date: 2019/12/30 15:04
 * @Description:
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private CommonResult commonResult;

    @Resource
    private RoleService roleService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HttpSession session = request.getSession();
        User ad = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        session.setAttribute(SessionKeyConst.USER, ad);
        //获取角色列表，存入session
        if (session.getAttribute(SessionKeyConst.ROLE) == null) {
            List<Role> roleList = roleService.selectAll();
            session.setAttribute(SessionKeyConst.ROLE, roleList);
        }

        // 装载权限
        commonResult.ajaxTrue("登录成功");
        String json = JSONUtil.toJsonStr(commonResult);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
